﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataObject.DataAccess;
using DataObject.Database;
using DataObject.Helpers;

public partial class Pages_Reservations_EmailConfirmation : System.Web.UI.Page
{

    #region Properties
    public Guid ReservationID
    {
        get
        {
            if (String.IsNullOrEmpty(Request["ReservationID"]))
                return Guid.Empty;
            return new Guid(Request["ReservationID"]);
        }
    }

    public string ConfirmationEmail
    {
        get
        {
            if (null != ViewState["ConfirmationEmail"]) return ViewState["ConfirmationEmail"].ToString();
            throw new NullReferenceException();
        }
        set
        {
            ViewState["ConfirmationEmail"] = value;
        }
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var reservationEntity = ReservationDAO.CreateInstant().GetReservationById(ReservationID);
            if (null != reservationEntity)
            {
                var guestEntity = GuestDAO.CreateInstant().GetGuestById(reservationEntity.GuestID);
                this.txtTo.Text = reservationEntity.ConfirmationEmail;
                this.txtCc.Text = "confirmation@mekongeyes.com";
                this.txtSubject.Text = "Booking confirmation (" + guestEntity.Title + " " + guestEntity.FullName + ")";
                this.elm1.InnerHtml = GetEmailConfirmation(reservationEntity, guestEntity);
            }
        }
    }

    protected void SendEmail(object sender, EventArgs e)
    {
        try
        {
            bool enableSsl;
            int port;
            string host, displayName, emailAddress, password;
            Helper.ReadConfigSMTP(out displayName, out host, out port, out emailAddress, out password, out enableSsl);

            string[] ccMails = this.txtCc.Text.Split(',');
            string[] bccMails = new string[] { "huutai.alz@gmail.com" };
            SendMail gmail = new SendMail(host, port, emailAddress, password);
            int i = gmail.Send(displayName, this.txtTo.Text, this.txtSubject.Text, HttpUtility.HtmlDecode
(this.elm1.InnerHtml), ccMails, bccMails);
            if (i != 1) throw new Exception("Send email failed.");

            this.Response.Redirect("/Pages/Reservations/ReservationList.aspx");
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            // throw new Exception("Send email failed.");
        }
    }
    #endregion

    #region Methods
    private string GetCabinNumber(Guid reservationID)
    {
        var reservationDetails = ReservationDetailDAO.CreateInstant().GetReservationDetailBy(reservationID);
        IList<string> cabin = new List<string>();
        int doubleBed = reservationDetails.Count(x => x.Status == 1);
        int twinBed = reservationDetails.Count(x => x.Status == 2);
        int singleBed = reservationDetails.Count(x => x.Status == 3);
        if (doubleBed > 0) cabin.Add(String.Format("{0:00} Double(s)", doubleBed));
        if (twinBed > 0) cabin.Add(String.Format("{0:00} Twin(s)", twinBed));
        if (singleBed > 0) cabin.Add(String.Format("{0:00} Single(s)", singleBed));

        return String.Join(", ", cabin.ToArray());
    }

    private string GetEmailConfirmation(Reservation reservation, Guest guest)
    {
        int currency = 0;
        decimal rate = 1M;
        string rooms = GetCabinNumber(reservation.ReservationID);
        string routeName = String.Empty;
        string price = GetPrice(reservation, out currency, out rate);
        decimal deposit = (reservation.Deposit + reservation.Paid) / rate;

        var route = RouteDAO.CreateInstant().GetAllRoutes().SingleOrDefault(x => x.RouteNumber == reservation.RouteNumber && x.SubRouteCode == reservation.SubRouteCode);
        if (null != route) routeName = route.RouteName;

        string filename = "template/emailconfirmation.htm";
        string filePath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath.Replace("/", "\\")) + "\\" + filename;
        string body = Helper.ReadTemplateFile(filePath);

        body = body.Replace("[tourname]", routeName);
        body = body.Replace("[bookingcode]", reservation.ReservationCode);
        body = body.Replace("[title]", guest.Title);
        body = body.Replace("[firstname]", guest.FirstName);
        body = body.Replace("[lastname]", guest.Lastname);
        body = body.Replace("[noofpax]", reservation.NumOfPax.ToString("#,##0"));
        body = body.Replace("[departuredate]", reservation.DepartureDate.ToLongDateString());
        body = body.Replace("[cabin]", rooms);
        body = body.Replace("[price]", price);
        body = body.Replace("[deposit]", String.Format("{0} {1:#,##0.##}", ((CurrencyEnum)currency).GetStringValue(), deposit));
        body = body.Replace("[hasdeposit]", deposit == 0 ? "No" : "Yes");
        body = body.Replace("[balance]", String.Format("{0} {1:#,##0.##}", ((CurrencyEnum)currency).GetStringValue(), (reservation.Balance / rate)));
        body = body.Replace("[haspickup]", reservation.IsShuttle ? "Yes" : "No");
        body = body.Replace("[pickuphotel]", reservation.HotelAddress);
        body = body.Replace("[phoneinvietnam]", "N/A");
        body = body.Replace("[internationalphone]", "N/A");
        body = body.Replace("[email]", reservation.ConfirmationEmail);
        // body = body.Replace("[hasreturn]", "N/A");
        // body = body.Replace("[returnhotel]", "N/A");

        return body;
    }

    private string GetPrice(Reservation reservation, out int currency, out decimal rate)
    {
        currency = reservation.CruiseCurrency;
        rate = reservation.CruiseRate;
        decimal price = reservation.CruisePackage + reservation.ShuttlePrice * reservation.NumOfPax + reservation.ExtraService;

        if (currency != -1)
            return String.Format("{0} {1:#,##0.##}", ((CurrencyEnum)currency).GetStringValue(), price);
        return String.Empty;
    }
    #endregion

}